import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_base/common/colors.dart';
import 'package:flutter_base/common/theme.dart';

/// Create： Zhang 3/18/21 11:32 AM
/// 描述：页面的基础类

abstract class BasePage extends StatefulWidget {
  //appContext页面导航的时候使用
  BasePage({
    this.title = "标题",
    this.isFirstPage = false,
    this.backIcon = Icons.arrow_back,
    this.titleColor = Colors.black87,
  });

  final String title; //标题
  final bool isFirstPage; //是否是第一个页面
  final IconData backIcon; //返回按钮图标
  final Color titleColor; //标题文字颜色

  //创建状态,由子类实现
  PageState createState();
}

class PageState extends State<BasePage> {
  //使用默认主题,带有appBar,设置页面内容
  @protected
  @factory
  Widget? content(BuildContext context) => null;

  //设置appBar右侧menu
  @protected
  @factory
  List<Widget>? actions(BuildContext context) => null;

  //覆写此方法则覆盖所有主题,与content()方法互斥
  @protected
  @factory
  Widget? rootView(BuildContext context) => null;

  //关闭应用
  void close() {
    if (Theme.of(context).platform == TargetPlatform.android) {
      //退出flutter应用,相当于小程序的关闭按钮
      SystemNavigator.pop();
    } else {
      exit(0);
    }
  }

  @override
  Widget build(BuildContext context) {
    setTranStatusBar(context);
    return createBody(context);
  }

  Widget createBody(BuildContext context) {
    return rootView(context) != null
        ? rootView(context)!
        : Scaffold(
            appBar: AppBar(
              //设置状态栏字体为黑色
              brightness: Brightness.light,
              title: Text(
                widget.title,
                style: TextStyle(color: widget.titleColor, fontSize: 18),
              ),
              elevation: 0,
              leading: widget.isFirstPage
                  ? null
                  : IconButton(
                      icon: Icon(Icons.arrow_back, color: widget.titleColor),
                      onPressed: () {
                        //如果是首页的话
                        if (widget.isFirstPage) {
                          close();
                        } else {
                          //不是首页返回上一页
                          Navigator.pop(context);
                        }
                      },
                    ),
              actions: actions(context),
            ),
            body: content(context),
            backgroundColor: bgColor,
          );
  }
}
